<template>
	<view class="content">
		<uni-list :border="true">
			<uni-list-chat clickable="true" v-for="(item,index) in data" @click="gotoMesage(item)"
				:title="item.showName" :avatar="item.faceUrl" :note="lastMessage(item.latestMsg)"
				:time="timeCacule(item.latestMsgSendTime)" badge-positon="left" :badge-text="item.unreadCount">
			</uni-list-chat>
		</uni-list>
		<view class="addFriends" @click="popAddFriends">
			+
		</view>
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog mode="input" title="添加好友" @confirm="confirm">
			</uni-popup-dialog>
		</uni-popup>

	</view>
</template>

<script>
	import * as opIm from '../../utils/openIm.js';
	import {
		date
	} from '../../utils/time.js'
	export default {
		data() {
			return {
				title: 'Hello',
				data: []
			}
		},
		onLoad() {
			// 登录IM
			this.loginIM(true);

			// 监听IM
			opIm.openIM.on('OnConversationChanged', (data) => {
				this.getConvsList();
				console.log('会话组监听到');
				console.log(data);
			});

		},
		methods: {
			popAddFriends() {
				this.$refs.popup.open()
			},
			confirm(text) {
				// 添加好友
				console.log(text);
				let data = {
					uid: text,
					reqMessage: "我是老妹"
				}
				opIm.addTheFriend(data);
			},
			async loginIM(refresh) {

				await opIm.loginIM('15658112878', '147258');

				// 获取用户信息
				let userInfo = await opIm.getUserInfo(['15658112878']);

				console.log(userInfo);
				uni.setStorage({
					key:'myInfo',
					data:JSON.parse(userInfo.data)[0]					
				})

				// 需要刷新列表
				if (refresh) {
					this.getConvsList();
				}
			},
			getConvsList() {
				// 获取会话列表
				console.log('调用');
				opIm.getConversationList().then((res) => {
					console.log(res);
					this.data = JSON.parse(res.data);
					console.log(this.data);
				})
			},
			gotoMesage(item) {
				console.log('xxxx');
				uni.navigateTo({
					url: './message?targetId=' + item.userID + '&groupId=' + item.groupID,
				})
			},
			timeCacule(time) {
				console.log(time);
				return date(time);
			},
			lastMessage(jsonMess) {
				console.log(jsonMess);
				let msg = JSON.parse(jsonMess);
				console.log(msg);

				if (msg.msgFrom == 200) {
					// 系统
					let content = JSON.parse(msg.content);
					return content.defaultTips;
				} else {
					// 用户
					//根据消息类型判别
					switch (msg.contentType){
						case 101:
						return msg.content;
						break;
						case 102:
						return '[图片]';
						break;
						case 103:
						return '[语音]';
						break;
						default:
							break;
					}
				}
			}
		}
	}
</script>

<style scoped>
	.content {
		height: 100%;
		width: 100%;
	}

	.addFriends {
		background-color: #F0AD4E;
		width: 100rpx;
		height: 100rpx;
		position: fixed;
		bottom: 130rpx;
		right: 40rpx;
		border-radius: 50rpx;
		color: white;
		font-size: 60rpx;
		text-align: center;
	}
</style>
